package com.finance.logistics.anlyzier;


import com.finance.base.constant.BaseConstants;
import com.finance.base.enums.ImportSourceEnum;
import com.finance.framework.lang.Privilege;
import com.finance.report.bean.pojo.LogisticsData;
import com.finance.system.bean.pojo.LogisticsColumnDef;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 运单来源解析类
 * Created by CBWL on 2017/4/27.
 */
@Component
public class ImportsourceHandler extends AbstractHandler {

    @Override
    @Resource(name="supplierHandler")
    public void setNextHandler(AbstractHandler nextHandler){
        super.setNextHandler(nextHandler);
    }

    @Override
    public void doHandler(LogisticsData logisticsData) {
        this.logger.info("待解析运单信息：{}", net.sf.json.JSONObject.fromObject(logisticsData).toString());
        Integer importSource = logisticsData.getImportSource();
        LogisticsColumnDef logisticsColumnDef = this.logisticsMappingService.getByClasz(this.getClass().getCanonicalName());
        if(logisticsColumnDef == null){
            this.logger.error("logisticsColumnDef is null 未知的运单列映射[clazz]",this.getClass().getCanonicalName());
            String errorReason = "未知的运单列映射[clazz]：{"+this.getClass().getCanonicalName()+"}";
            this.logisticsErrorLogService.addErrorLog(logisticsData,errorReason,BaseConstants.ANALYZE_ERROR_TYPE_IMPORTSOURCE);
        }else{
            int target = HandlerHelper.analyze(importSource,logisticsColumnDef);
            if(target == -1){
                this.logger.error("未知的运单列映射[importSource]{}",importSource);
                target = ImportSourceEnum.SYSTEM_ACCESS.getValue();//给默认值
                this.defaultHandler(target,logisticsData);
            }else{
                this.defaultHandler(target,logisticsData);
            }
        }
    }
    
    private void defaultHandler(int target,LogisticsData logisticsData){
        String tableName = this.logisticsDataService.getDataTableName(logisticsData.getSignTime());
        LogisticsData logisticsData2update = this.logisticsDataService.getByWaybillNum(tableName,logisticsData.getWaybillNum());
        logisticsData2update.setImportSource(target);
        try {
            this.logisticsDataService.update(logisticsData2update);
            this.updateDataVild(logisticsData2update,Privilege.B3);
            this.getNextHandler().doHandler(logisticsData);
        } catch (Exception e) {
            this.logger.info("运单来源字段更新异常[importSource]:{}",e.getMessage());
            logger.error(e.getMessage(),e);
        }
    }
}
